package com.seres.user.service.oplog;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seres.client.mapper.log.SysLogMapper;
import com.seres.client.model.log.SysLog;
import com.seres.client.model.user.SysUser;
import com.seres.client.vo.LogReq;
import com.seres.client.vo.LogRes;
import com.seres.config.CacheInterface;
import com.seres.redis.RedisTableCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class SysLogServiceImpl implements ISysLogService {

    @Resource
    private SysLogMapper logMapper;

    @Resource
    private RedisTableCache redisTableCache;

    @Resource
    private CacheInterface urlCache;


    @Override
    public IPage<LogRes.Pages> getLogPage(Page<SysLog> page, LogReq req) {
        LambdaQueryWrapper<SysLog> wrapper = Wrappers.lambdaQuery(SysLog.class)
                .eq(req.getCode() != null, SysLog::getCode, req.getCode())
                .eq(StringUtils.isNotBlank(req.getIp()), SysLog::getIp, req.getIp())
                .eq(req.getUserId() != null, SysLog::getUserId, req.getUserId())
                .eq(req.getType() != null, SysLog::getType, req.getType())
                .eq(StringUtils.isNotBlank(req.getMethodType()), SysLog::getMethodType, req.getMethodType())
                .like(StringUtils.isNotBlank(req.getTitle()), SysLog::getTitle, req.getTitle())
                .like(StringUtils.isNotBlank(req.getModuleName()), SysLog::getModuleName, req.getModuleName())
                .like(StringUtils.isNotBlank(req.getUrl()), SysLog::getUrl, req.getUrl()).orderByDesc(SysLog::getId);
        return logMapper.selectPage(page, wrapper).convert(e -> {
            LogRes.Pages pages = BeanUtil.copyProperties(e, LogRes.Pages.class);
            if (pages.getUserId() != null) {
                SysUser user = redisTableCache.get(SysUser.class, pages.getUserId());
                if(user!=null){
                    pages.setUserName(user.getUserName());
                }
            }
            return pages;
        });
    }

}
